<template>
  <div class="i18n-generator">
    <div class="navs">
      <el-tabs v-model="editableTabsValue" type="card" class="navs-tabs">
        <el-tab-pane v-for="item in editableTabs" :key="item.name" :label="item.title" :name="item.name">
        </el-tab-pane>
      </el-tabs>
      <div class="i18-tools">
        <el-upload drag :auto-upload="false" v-model:file-list="fileList">
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            Drop file here or <em>click to upload</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              JS/JSON files with a size less than 500kb
            </div>
          </template>
        </el-upload>
      </div>
    </div>
    <div class="i18n-generator--wrapper">
      <div class="i18n-generator--wrapper-box">
        <el-table v-loading="loading" :data="tableData" border height="100%" row-key="id">
          <el-table-column prop="key" label="字段" width="250">
            <template #default="{row}">
              <el-input v-model="row.key"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="value" label="值">
            <template #default="{row}">
              <div class="operate">
                <div class="i18-input-value">
                  <el-input v-model="row.value"></el-input>
                </div>
                <el-button @click="addSubitem(row)" :icon="Plus">添加子项</el-button>
                <el-button @click="deleteLine(row)" :icon="Delete" type="danger">删除项目</el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="operate">
            <template #header="{row}">
              <el-button @click="addLine" :icon="Upload">上传后点击解析</el-button>
              <el-button @click="generate" :icon="Tickets">生成内容</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
  <el-dialog v-model="codeShow" title="Shipping address" width="80%" height="80vh">
    <el-input
      v-model="codeText"
      type="textarea"
      :rows="30"
      placeholder="Please input"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import { Plus, Delete, Edit, Tickets, Share, Upload } from '@element-plus/icons-vue'
import { table } from 'console';
import { nextTick } from 'vue';

const data: any = reactive({
  editableTabsValue: "",
  editableTabs: [],
  totalData: [],
  tableData: [],
  fileList: [],
  loading: false,
  codeShow: false,
  codeText: ''
});
const {
  tableData,
  totalData,
  editableTabsValue,
  editableTabs,
  fileList,
  loading,
  codeShow,
  codeText
} = toRefs(data);

watch(
  () => fileList.value,
  (val, preVal) => {
    loading.value = true;
    editableTabsValue.value = "";
    editableTabs.value = [];
    tableData.value = [];
    totalData.value = [];
    val.map((im:any)=>{
      readFileContent(im);
    })
  },
  { immediate: false, deep: true },
);

watch(
  () => editableTabsValue.value,
  (val, preVal) => {
    const currentData = totalData.value.find((im:any)=>im.key == val);
    tableData.value = currentData.value;
    nextTick(()=>{
      loading.value = false;
    });
  },
  { immediate: false, deep: true },
);


// 迭代器
const iteration = (object:any) => {
  const res: any = [];
  for (const key in object) {
    if (Object.prototype.hasOwnProperty.call(object, key)) {
      const element = object[key];
      let obj:any = {
        id: key,
        key: key,
      }
      if(typeof element === 'string'){
        obj.value = element;
      }else{
        obj.children = iteration(element);
      }
      res.push(obj);
    }
  }
  return res;
}


tableData.value = iteration({
  lang: {
    el: {
      datepicker: {
        now: '此刻',
        today: '今天',
        cancel: '取消',
        clear: '清空',
        confirm: '确定',
        selectDate: '选择日期',
        selectTime: '选择时间',
        startDate: '开始日期',
        startTime: '开始时间',
        endDate: '结束日期',
        endTime: '结束时间',
        prevYear: '前一年',
        nextYear: '后一年',
        prevMonth: '上个月',
        nextMonth: '下个月',
        year: '年',
        month1: '1 月',
        month2: '2 月',
        month3: '3 月',
        month4: '4 月',
        month5: '5 月',
        month6: '6 月',
        month7: '7 月',
        month8: '8 月',
        month9: '9 月',
        month10: '10 月',
        month11: '11 月',
        month12: '12 月',
        // week: '周次',
        weeks: {
          sun: '日',
          mon: '一',
          tue: '二',
          wed: '三',
          thu: '四',
          fri: '五',
          sat: '六'
        },
        months: {
          jan: '一月',
          feb: '二月',
          mar: '三月',
          apr: '四月',
          may: '五月',
          jun: '六月',
          jul: '七月',
          aug: '八月',
          sep: '九月',
          oct: '十月',
          nov: '十一月',
          dec: '十二月'
        },
      },
      select: {
        noMatch: "未找到查询内容",
        noData: "暂未开启"
      },
      pagination: {
        pagesize: "页"
      }
    }
  },
  vip: {
    Bankroll: '游戏奖池',
    Segment: '部分',
    title: '中奖记录',
    Leaderboard: '排行榜',
    Explain: '解释',
    FreeSpin: '自由旋转',
    Countdowntothedraw: '抽奖倒计时',
    Nextfreespinbonus: '下一个免费旋转奖金',
    RebateRatio: '返利比例',
    CheckoutNow: '立即结帐',
    VIP24open: 'VIP 24 开放',
    Winnerofthepreviousissue: '上一期的获奖者',
    Ranking: '排行',
    Eventstartscountdown: '活动开始倒计时',
    AutomaticSettlementCountdown: '自动结算倒计时',
    Curentunsettledbetamout: '目前未结清押注金额',
    Avitivitytime: '',
    Every12hours: '每隔12小时，使用rain算法从聊天室中抽取6名玩家，发放DC奖励。',
    Onlytheplayer: '只有说话的玩家才能获得奖励。您发送的消息越多，您获胜的机会就越大，请随时发表您的意见。',
    AbouttherewardUgame: '关于奖励：将实时发出，并在站内通知',
    Every48hours: '每48小时会为聊天室Vip12以上的所有成员发放奖金。',
    Justclick: '只需在相应时间内点击宝箱即可获得现金奖励',
    AbouttherewardGolden: '关于奖励：将实时发出，并在站内通知',
    Ifthenumbers: '如果数字相同，它们将按时间',
    Thereis1lotter: '每天有1次抽奖机会，从1到9999，号码从大到小，当日平台前10名玩家可以获得等量的JB。',
    Aboutthereward: '关于奖励：每天0:00自动发放，请记得前来领取',
    ThehighertheVIP: 'VIP等级越高，每日返还率越高。',
    AutomaticSettlement: '每天0:00自动结算。',
    PlayersreachVIP24: '玩家达到VIP24解锁：即时返现。',
    TherankingisUpdated: '排名每天0点更新',
    Oddswinning: "• 1. 转盘中奖概率为100%。",
    OddRules: "• 2.开奖次数每天0:00刷新，请记得使用。",
    OddQuestion: "• 3. 如有任何问题，请咨询【客服】。",
    about: "关于奖励：每天0:00自动发放，请注意查收",
    fee: "提现手续费",
    day: "每日提款",
    times: "次",
    limit: "每日提款上限",
  },
});


// 添加子项
const addSubitem = (row:any) => {
  !row.children && (row.children = []);
  row.children.push({
    id: new Date().getTime(),
    key: 'sub key',
    value: 'sub value'
  });
}

// 添加行
const addLine = () => {
  tableData.value.push({
    id: new Date().getTime,
    key: "Fill in key",
    value: "Fill in value",
  })

}

// 修改文件
const readFileContent = (f: any) => {
  const file = f.raw;
  // 检测浏览器对FileReader的支持
  if(window.FileReader) {
      // 创建FileReader对象(文件对象)
    const reader = new FileReader();
    /*----------    6种事件模型    ---------*/
    // 开始读取时：
    reader.onloadstart = function(e) {
      // console.log("开始读取", e);
    };
    // 正在读取：
    reader.onprogress = function(e) {
      // console.log("正在读取", e);
    };
    // 读取出错时：
    reader.onerror = function(e) {
      // console.log("读取出错", e);
    };
    // 读取中断时：
    reader.onabort = function(e) {
      // console.log("读取中断", e);
    };
    // 读取成功时：
    reader.onload = function(e:any) {
      // console.log("读取成功", e, f.name);
      if(/.js$/i.test(f.name)){
        let time = new Date().getTime();
        let res = e.target.result.replace("=", time).split(time)[1];
        // console.log("JS文件", res)
      }else if(/.json$/i.test(f.name)){
        let res = e.target.result;
        // console.log("JSON文件", JSON.parse(res));
        editableTabs.value.push({
          title: f.name,
          name: f.name,
        });
        totalData.value.push({
          key: f.name,
          value: iteration(JSON.parse(res))
        });
        editableTabsValue.value = f.name;
      }
    };

    if(/image\/\w+/.test(file.type)){
      reader.readAsDataURL(file);
    }else{
      // 输出文件
      reader.readAsText(file, "utf-8");
    };
  }else {
      alert("Not supported by your browser!");
  };
}

// 生成内容
const generate = () => {
  codeText.value = JSON.stringify(readContentToString(tableData.value));
  codeShow.value = true;
}

// 对象生成字符串
const readContentToString = (array:any) => {
  const res: any = {};
  array.map((item:any) => {
    if(item.children && item.children.length > 0){
      res[item.key] = readContentToString(item.children);
    }else{
      res[item.key] = item.value;
    }
  })
  return res;
}

const deleteLine = (row:any) => {
  deleteObjectLine(tableData.value, row)
}

const deleteObjectLine = (target:any, row:any) => {
  target.map((item:any, index: number)=>{
    if(item.id === row.id){
      target.splice(index, 1);
    }else{
      if(item.children && item.children.length > 0){
        deleteObjectLine(item.children, row);
      }else{
        // item.splice(index, 1);
      }
    }
  })
}

</script>

<style lang="scss" scoped>
@import url(./index.scss);
</style>
